package com.jiulan.hearthearing.ui.cart.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseActivity;
import com.jiulan.hearthearing.base.BaseModel;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.cart.adapter.CartAdapter;
import com.jiulan.hearthearing.ui.cart.model.CartModel;
import com.jiulan.hearthearing.ui.cart.util.CartUtil;
import com.jiulan.hearthearing.ui.pay.activity.SettlementDeskActivity;
import com.jiulan.hearthearing.utils.StringUtils;
import com.jiulan.hearthearing.widget.SpaceVerticalItemDecoration;
import com.jiulan.hearthearing.widget.WarningDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车
 */
public class CartActivity extends BaseActivity implements View.OnClickListener {
    private boolean isSelectAll = true;
    private List<CartModel.DataBean.ValidBean> data;
    private CartAdapter cartAdapter;
    private int tag = 1;//1-结算，2-删除等操作

    private ImageView _barBack;
    private TextView _barTitle;
    private TextView _barTvRight;
    private RecyclerView mRecyclerView;
    private ImageView ivSelectAll;
    private TextView tvYingfu;
    private TextView tvDelete;
    private TextView tvConfirmPay;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, CartActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_cart;
    }

    @Override
    protected void initView() {
        _barBack = findViewById(R.id._barBack);
        _barTitle = findViewById(R.id._barTitle);
        _barTvRight = findViewById(R.id._barTvRight);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        ivSelectAll = findViewById(R.id.ivSelectAll);
        tvYingfu = findViewById(R.id.tvYingfu);
        tvDelete = findViewById(R.id.tvDelete);
        tvConfirmPay = findViewById(R.id.tvConfirmPay);
        _barBack.setOnClickListener(this);
        _barTvRight.setOnClickListener(this);
        ivSelectAll.setOnClickListener(this);
        tvDelete.setOnClickListener(this);
        tvConfirmPay.setOnClickListener(this);
        _barTitle.setText("购物车");
        _barTvRight.setVisibility(View.VISIBLE);
        setState();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new SpaceVerticalItemDecoration(getContext(),R.dimen.fab_margin));
        getData();
    }

    @Override
    protected void initData() {

    }

    /**
     * 购物车数据
     */
    private void getData() {
        Map<String, String> map = new HashMap<>();
        new HttpRequest(getContext()).doGet(UrlConstants.cart_list, "", map, CartModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof CartModel) {
                    CartModel cartModel = (CartModel) result;
                    data = cartModel.getData().getValid();
                    setView();
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private void setView() {
        CartUtil.selectAll(data, !isSelectAll);
        CartUtil.checkItem(isSelectAll, ivSelectAll);
        cartAdapter = new CartAdapter(data);
        mRecyclerView.setAdapter(cartAdapter);
        tvYingfu.setText("¥" + CartUtil.getTotalPrice(data));
        cartAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.ivSelect:
                        boolean isSelect = !data.get(position).isSelect();
                        ImageView ivSelect = (ImageView) view;
                        CartUtil.checkItem(isSelect, ivSelect);
                        data.get(position).setSelect(isSelect);
                        w:
                        for (int i = 0; i < data.size(); i++) {
                            CartModel.DataBean.ValidBean validBean = data.get(i);
                            boolean isItemSelect = validBean.isSelect();
                            if (isItemSelect) {
                                isSelectAll = true;
                            } else {
                                isSelectAll = false;
                                break w;//根据标记，跳出嵌套循环
                            }
                        }
                        CartUtil.checkItem(isSelectAll, ivSelectAll);
                        tvYingfu.setText("¥" + CartUtil.getTotalPrice(data));
                        break;
                }
            }
        });
    }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id._barBack:
                finish();
                break;
            case R.id._barTvRight:
                if (tag == 1) {//1-结算，2-删除等操作
                    tag = 2;
                } else {
                    tag = 1;
                }
                setState();
                break;
            case R.id.ivSelectAll:
                CartUtil.selectAll(data, isSelectAll);
                isSelectAll = !isSelectAll;
                CartUtil.checkItem(isSelectAll, ivSelectAll);
                tvYingfu.setText("¥" + CartUtil.getTotalPrice(data));
                cartAdapter.notifyDataSetChanged();
                break;
            case R.id.tvConfirmPay:
                SettlementDeskActivity.actionStart(getContext(),StringUtils.ListToStringOne(CartUtil.getSelectGoodsIds(data)));
                break;
            case R.id.tvDelete:
                if (CartUtil.hasSelectedGoods(data)) {
                    WarningDialog ddialog = new WarningDialog(getContext(), "确定将所选宝贝删除？", "取消", "删除");
                    ddialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                        @Override
                        public void doCancel() {

                        }

                        @Override
                        public void doConfirm() {
                            delete(StringUtils.ListToStringOne(CartUtil.getSelectGoodsIds(data)));
                        }
                    });
                    ddialog.show();
                } else {
                    Toast.makeText(getContext(), "您还没有选择宝贝哦", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 删除购物车中的商品
     */
    private void delete(String ids) {
        Map<String, String> map = new HashMap<>();
        map.put("ids", ids);
        new HttpRequest(getContext()).doPost(UrlConstants.cart_del, "", map, BaseModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof BaseModel) {
                    BaseModel baseModel = (BaseModel) result;
                    if (baseModel.getStatus() == 200){
                        getData();
                    }else {
                        Toast.makeText(getContext(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private void setState() {
        switch (tag) {
            case 1:
                _barTvRight.setText("管理");
                tvConfirmPay.setVisibility(View.VISIBLE);
                tvDelete.setVisibility(View.GONE);
                break;
            case 2:
                _barTvRight.setText("完成");
                tvConfirmPay.setVisibility(View.GONE);
                tvDelete.setVisibility(View.VISIBLE);
                break;
        }
    }
}
